// pages/sales/boss_ai/selDepartment.js
var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
var app = getApp();
Page(Object.assign({}, baseHandle,{

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    tips:"温馨提示：点击部门名称查看下级部门",
    identifyMap: {},//{key:list}  key: parent's identify, list: children departments， 缓存list
    curList:[],//当前部门列表
    identifyHistory: [],// identify 历史栈
    isLoading:false,
    showReturn:false,
    saveKey:"",//选择时需要保持的 参数，xx,yy 选定时会把参数保存到上一个页面
    isShowAll: false,//顶级部门 默认有一个 全部条目
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    var ctx = this;
    ctx.setData({
      saveKey: options.saveKey,
      isShowAll: options.isShowAll == "n" ? false : true
    });
    app.getUserInfo(ctx, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      ctx.queryDepartments(null);
    });
  },
  //查询部门  
  /** upIdentify 上级部门的 identify
   *  isReturn 是否返回上一层
   */
  queryDepartments(upIdentify, isReturn, departName){
    wx.showLoading({
      title: "加载中..."
    });
    var ctx = this;
    var identifyHistory = ctx.data.identifyHistory;
    if (!isReturn) {//如果是返回操作 就不要 把 identify 存入历史栈

      identifyHistory.push({
        upIdentify: upIdentify,
        departName: departName
      });
      ctx.setData({
        identifyHistory: identifyHistory
      });
    }
    // 如果之前有缓存直接从缓存中拿
    if (upIdentify && ctx.data.identifyMap[upIdentify]){
      ctx.setData({
        curList: ctx.data.identifyMap[upIdentify],
        showReturn:true
      });
      wx.hideLoading();
      return;
    } else if (!upIdentify && ctx.data.identifyMap["root"]){
      ctx.setData({
        curList: ctx.data.identifyMap["root"],
        showReturn:false
      });
      wx.hideLoading();
      return;
    }
    if (ctx.data.isLoading){
      return;
    }
    ctx.setData({
      isLoading: true
    });
    ///applet/mobile/visitcard/department/queryDepartments
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/department/queryDepsByEmpPrivilege",
      data: {
        cusmallToken: cusmallToken,
        upIdentify: upIdentify || ""
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        wx.hideLoading();
        if (data && 0 === data.ret) {

          if (upIdentify){
            ctx.setData({
              ["identifyMap." + upIdentify]: data.model.list,
              curList: data.model.list,
              showReturn:true
            });
          }else{
            if (ctx.data.isShowAll){
              data.model.list.unshift({
                name: "全部",
                id: "",
                identify: "",
                upIdentify: ""
              });//顶级部门 默认一个全部
            }
            
            ctx.setData({
              ["identifyMap.root"]: data.model.list,
              curList: data.model.list,
              showReturn:false
            });
          }
        } else {
          wx.showToast({
            title: data.msg,
            icon: "none"
          })
        }
      },
      fail() {

      },
      complete() {
        ctx.setData({ 
          isLoading: false 
        });
      }
    });
  },
  returnLastList:function(){
    var ctx = this;
    // var idx = e.currentTarget.dataset.idx;
    // var depart = ctx.data.curList[idx];
    console.log(ctx.data.identifyHistory)
    var identifyHistory = ctx.data.identifyHistory;
    identifyHistory.pop();
    if (identifyHistory[identifyHistory.length - 1] && identifyHistory[identifyHistory.length - 1].departName){
      ctx.setData({
        tips: "上级部门：" + identifyHistory[identifyHistory.length - 1].departName
      });
    }else{
      ctx.setData({
        tips: "选择部门"
      });
    }
    
    ctx.setData({
      identifyHistory: identifyHistory
    });
    ctx.queryDepartments(identifyHistory[identifyHistory.length - 1].upIdentify, true);
  },
  nextDepartment(e){
    var ctx = this;
    var idx = e.currentTarget.dataset.idx;
    var depart = ctx.data.curList[idx];
    if (depart.isParent){

      ctx.queryDepartments(depart.identify, false, depart.name);
      ctx.setData({
        tips: "上级部门：" + depart.name
      });
    }else{
      wx.showToast({
        title:"当前部门无下级子部门",
        icon:"none",
        duration:1000
      })
    }
    console.log("next department");
  },
  doneSel(e){
    console.log("done select");
    var ctx = this;
    var idx = e.currentTarget.dataset.idx;
    var depart = ctx.data.curList[idx];
    var saveKeyArr = (ctx.data.saveKey && ctx.data.saveKey.split(",")) || [];
    console.log(depart)
    var sate = {};
    for (var i in saveKeyArr){
      sate[saveKeyArr[i]] = depart[saveKeyArr[i]];
    }
    let pages = getCurrentPages();//当前页面
    let prevPage = pages[pages.length - 2];//上一页面
    //直接给上移页面赋值
    prevPage.setData(sate);
    if (prevPage.selDepartmentCallback && "function" === typeof (prevPage.selDepartmentCallback)){
      prevPage.selDepartmentCallback(depart);
    }
    wx.navigateBack({
      delta: 1
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
}))